#!/bin/bash

# Minidis 健康检查脚本
# 用于监控服务器状态

set -e

# 默认配置
REDIS_HOST=${REDIS_HOST:-127.0.0.1}
REDIS_PORT=${REDIS_PORT:-6379}
TIMEOUT=${TIMEOUT:-3}
VERBOSE=${VERBOSE:-false}

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() {
    if [ "$VERBOSE" = "true" ]; then
        echo -e "$1"
    fi
}

check_connection() {
    log "${YELLOW}检查连接到 $REDIS_HOST:$REDIS_PORT...${NC}"

    if ! nc -z -w $TIMEOUT $REDIS_HOST $REDIS_PORT 2>/dev/null; then
        echo -e "${RED}❌ 无法连接到 $REDIS_HOST:$REDIS_PORT${NC}"
        return 1
    fi

    log "${GREEN}✅ 连接成功${NC}"
    return 0
}

check_ping() {
    log "${YELLOW}测试 PING 命令...${NC}"

    local response=$(echo -e '*1\r\n$4\r\nPING\r\n' | nc -w $TIMEOUT $REDIS_HOST $REDIS_PORT 2>/dev/null)

    if echo "$response" | grep -q "PONG"; then
        log "${GREEN}✅ PING 响应正常${NC}"
        return 0
    else
        echo -e "${RED}❌ PING 命令失败，响应: $response${NC}"
        return 1
    fi
}

check_basic_operations() {
    log "${YELLOW}测试基本操作...${NC}"

    # 测试 SET
    local set_response=$(echo -e '*3\r\n$3\r\nSET\r\n$11\r\nhealthcheck\r\n$2\r\nOK\r\n' | nc -w $TIMEOUT $REDIS_HOST $REDIS_PORT 2>/dev/null)

    if ! echo "$set_response" | grep -q "OK"; then
        echo -e "${RED}❌ SET 命令失败${NC}"
        return 1
    fi

    # 测试 GET
    local get_response=$(echo -e '*2\r\n$3\r\nGET\r\n$11\r\nhealthcheck\r\n' | nc -w $TIMEOUT $REDIS_HOST $REDIS_PORT 2>/dev/null)

    if ! echo "$get_response" | grep -q "OK"; then
        echo -e "${RED}❌ GET 命令失败${NC}"
        return 1
    fi

    # 清理测试键
    echo -e '*2\r\n$3\r\nDEL\r\n$11\r\nhealthcheck\r\n' | nc -w $TIMEOUT $REDIS_HOST $REDIS_PORT >/dev/null 2>&1

    log "${GREEN}✅ 基本操作正常${NC}"
    return 0
}

get_server_info() {
    if [ "$VERBOSE" = "true" ]; then
        log "${YELLOW}获取服务器信息...${NC}"
        echo -e '*1\r\n$4\r\nINFO\r\n' | nc -w $TIMEOUT $REDIS_HOST $REDIS_PORT 2>/dev/null
    fi
}

main() {
    local exit_code=0

    echo "🏥 Minidis 健康检查"
    echo "=================="
    echo "目标: $REDIS_HOST:$REDIS_PORT"
    echo "超时: ${TIMEOUT}s"
    echo ""

    # 执行检查
    if ! check_connection; then
        exit_code=1
    elif ! check_ping; then
        exit_code=1
    elif ! check_basic_operations; then
        exit_code=1
    else
        echo -e "${GREEN}🎉 所有检查通过！服务器健康状态良好${NC}"
        get_server_info
    fi

    exit $exit_code
}

# 处理命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--host)
            REDIS_HOST="$2"
            shift 2
            ;;
        -p|--port)
            REDIS_PORT="$2"
            shift 2
            ;;
        -t|--timeout)
            TIMEOUT="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        --help)
            echo "用法: $0 [选项]"
            echo ""
            echo "选项:"
            echo "  -h, --host HOST      Redis 服务器地址 (默认: 127.0.0.1)"
            echo "  -p, --port PORT      Redis 服务器端口 (默认: 6379)"
            echo "  -t, --timeout SEC    连接超时时间 (默认: 3)"
            echo "  -v, --verbose        详细输出"
            echo "      --help           显示帮助信息"
            echo ""
            echo "环境变量:"
            echo "  REDIS_HOST           Redis 服务器地址"
            echo "  REDIS_PORT           Redis 服务器端口"
            echo "  TIMEOUT              连接超时时间"
            echo "  VERBOSE              详细输出 (true/false)"
            exit 0
            ;;
        *)
            echo "未知选项: $1"
            echo "使用 --help 查看帮助信息"
            exit 1
            ;;
    esac
done

main